﻿using System;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Services;

namespace mozhi.smarterp.BasicData.Units.Service
{
    public class UnitManager : DomainService
    {
        private IUnitRepository _repository;

        public UnitManager(IUnitRepository repository)
        {
            _repository = repository;
        }

        public async Task<Unit> CreateAsync(Guid id, string code, string name, bool activated)
        {
            var matchCount = await _repository.GetCountAsync(code, null, null) + await _repository.GetCountAsync(null, name, null);

            if (matchCount > 0)
                throw new UserFriendlyException("编码或者名称已经存在", "100000");

            var unit = new Unit(id, code, name, activated);

            return unit;
        }

        public async Task<Unit> UpdateAsync(Guid id, string code, string name, bool activated)
        {
            var unit = await _repository.GetAsync(id);

            if (unit == null)
                throw new BusinessException($"单位：{id}不存在", "100000");

            var matchCount = await _repository.GetCountAsync(code, null, id) + await _repository.GetCountAsync(null, name, id);

            if (matchCount > 0)
                throw new UserFriendlyException("编码或者名称已经存在", "100000");

            unit.Change(code, name, activated);

            return unit;
        }
    }
}
